package cn.xiaopengstack.domain.strategy.model.entity;

import cn.xiaopengstack.domain.strategy.model.valobj.RuleTreeNodeVO;
import cn.xiaopengstack.domain.strategy.service.rule.filter.factory.DefaultLogicFactory;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

/**
 * @author jiangyangang
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class StrategyAwardEntity {
    /**
     * 自增ID
     */
    private Long id;

    /**
     * 抽奖策略ID
     */
    private Long strategyId;

    /**
     * 抽奖奖品ID - 内部流转使用
     */
    private Integer awardId;

    /**
     * 抽奖奖品标题
     */
    private String awardTitle;

    /**
     * 抽奖奖品副标题
     */
    private String awardSubtitle;

    /**
     * 奖品库存总量
     */
    private Integer awardCount;

    /**
     * 奖品库存剩余
     */
    private Integer awardCountSurplus;

    /**
     * 奖品中奖概率
     */
    private BigDecimal awardRate;

    /**
     * 规则模型，rule配置的模型同步到此表，便于使用
     */
    private String ruleModels;

    /**
     * 排序
     */
    private Integer sort;

    /**
     * 是否被锁定
     */
    private Boolean locked;

    /**
     * 剩余解锁次数
     */
    private Integer unlockTimes;

    /**
     * 创建时间
     */
    private Date createTime;

    /**
     * 修改时间
     */
    private Date updateTime;

    /**
     * 结束时间
     */
    private Date endTime;

    /**
     * 设置锁定信息
     * @param treeNodeMap
     * @param userWinAwardCount
     */
    public void doInitLock(Map<String, RuleTreeNodeVO> treeNodeMap, int userWinAwardCount) {
        String ruleLock = DefaultLogicFactory.LogicModel.RULE_LOCK.getCode();

        int unLockTimes = 0;
        int lockTimes = 0;

        // 计算剩余解锁次数
        if (treeNodeMap.containsKey(ruleLock)) {
            RuleTreeNodeVO nodeVO = treeNodeMap.get(ruleLock);
            unLockTimes = Integer.parseInt(nodeVO.getRuleValue());
            lockTimes = userWinAwardCount == 0 ? unLockTimes : Math.abs((userWinAwardCount % unLockTimes) - unLockTimes);
        }

        this.setUnlockTimes(lockTimes);
        this.setLocked(1 <= lockTimes);
    }
}
